/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package APP2.bookshop.controller;

import APP2.bookshop.book.Book;
import APP2.bookshop.author.Author;
import APP2.bookshop.main.BookShop;
import APP2.bookshop.publisher.Publisher;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComboBox;

/**
 *
 * @author finalfire
 */
public class PublisherController {

    private BookShop bookshop;

    public PublisherController(BookShop bookshop) {
        this.bookshop = bookshop;
    }

    public boolean addPublisher(String name, String email, String phone, String postcode) {
        if (name != null && email != null && phone != null && postcode != null) {
            this.bookshop.getPublishers().add(new Publisher(name, email, phone, postcode));
            return true;
        }

        return false;
    }

    public boolean deletePublisher(Publisher p) {
        // delete from books
        for (Book b : p.getBooks())
            b.setPublisher(null);
        // delete from bookshop
        if (this.bookshop.getPublishers().remove(p))
            return true;
        return false;
    }

    public Publisher getPublisherByName(String name) {
        Publisher corr = null;
        for (Publisher p : this.bookshop.getPublishers())
            if (p.getName().equals(name))
                corr = p;
        return corr;
    }

    public javax.swing.ComboBoxModel getPublishersCombo() {
        JComboBox model = new JComboBox(this.getPublishersArray());
        return model.getModel();
    }

    // Return an AbstractListModel for JList component
    public javax.swing.AbstractListModel getPublishersModel() {
        // create a new array to save authors' name
        //final String[] elements = new String[this.bookshop.getPublishers().size()];
        //for (int i = 0; i < elements.length; i++)
            //elements[i] = this.bookshop.getPublishers().get(i).getName();

        // return a new AbstractListModel
        return UtilController.getListModelFromArray(this.getPublishersArray());
    }

    public javax.swing.AbstractListModel getAllBooksByPublisher(String name) {
        return this.getAllBooksByPublisher(this.getPublisherByName(name));
    }
    public javax.swing.AbstractListModel getAllBooksByPublisher(Publisher p) {
        String[] books = new String[p.getBooks().size()];
        int i = 0;
        for (Book b : p.getBooks()) {
            books[i] = b.getTitle();
            i++;
        }
        return UtilController.getListModelFromArray(books);
    }

    private String[] getPublishersArray() {
        String[] pubs = new String[this.bookshop.getPublishers().size()];
        for (int i = 0; i < pubs.length; i++)
            pubs[i] = this.bookshop.getPublishers().get(i).getName();
        return pubs;
    }
}
